package com.fisher.checker;

import static android.view.View.FOCUS_UP;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.os.Vibrator;
import android.provider.DocumentsContract;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.fisher.checker.db.DatabaseClient;
import com.fisher.checker.db.DatabaseManager;
import com.fisher.checker.db.dao.ProductItemDao;
import com.fisher.checker.db.entity.ProductItemEntity;
import com.fisher.checker.item.ProductItem;
import com.fisher.checker.item.ProductItemContainer;
import com.fisher.checker.product.Product;
import com.fisher.checker.product.ProductDB;
import com.google.android.material.tabs.TabLayout;
import com.honeywell.aidc.AidcManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final String YOUR_PASSWORD = "admin@2024";

    // 头部组件
    private LinearLayout headerLayout;
    private TextView fixedText;

    // 内容组件
    private LinearLayout contentLayout;
    private TableLayout tableProduct;

    private TableRow trElectron1;
    private TableRow trElectron2;
    private TableRow trElectron3;
    private TableRow trElectron4;


    private EditText etScan;
    private EditText etProductBarcode;
    private EditText etProductNo;
    private EditText etProductNm;
    private ImageView imgProduct;
    private EditText etElectronBarcode;
    private EditText etElectronNo;
    private EditText etElectronNm;
    private ImageView imgElectron;
    private EditText etSuccessCount;
    private TextView txCheckResult;
    private Spinner spinProductNo;
    private ProgressBar progressBar;
    private Button btnActivate;

    private TableRow trNewScan;
    private Product currentProduct;

    private Map<String, ProductItemContainer> containerMap = new LinkedHashMap<>();
    private ProductItemContainer currentContainer;

    private final List<String> electronCodes = new ArrayList<>();

    // 0  是 product  1是 electron
    private int operator;

    private Vibrator vibrator;

    private MediaPlayer mediaPlayer;
    private AidcManager manager;
    private static final int REQUEST_CODE_PERMISSION = 100;
    private ProductItemDao productItemDao;

    private String currentContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        currentContent = null;
        progressBar = findViewById(R.id.progressBar);
        AidcManager.create(this, new AidcManager.CreatedCallback() {

                    @Override
                    public void onCreated(AidcManager aidcManager) {
                        manager = aidcManager;
                        if(manager == null){
                            trNewScan.setVisibility(GONE);
                            Toast.makeText(MainActivity.this, "Scanner not found![AidcManager]", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if(manager.listConnectedBarcodeDevices() == null||manager.listConnectedBarcodeDevices().size() == 0){
                            trNewScan.setVisibility(GONE);
                            Toast.makeText(MainActivity.this, "Scanner not found!", Toast.LENGTH_LONG).show();
                            return;
                        }
                        checkActivate();
                    }
                });


        btnActivate = findViewById(R.id.btn_activate);
        btnActivate.setVisibility(GONE);
        etScan = findViewById(R.id.et_scan);
        trNewScan = findViewById(R.id.tr_new_scan);
 // //zhy 签名的方式判断激活 --start
//        btnActivate.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                PrivateKeyInputDialog.showPrivateKeyInputDialog(MainActivity.this, new PrivateKeyInputDialog.PrivateKeyListener() {
//                    @Override
//                    public void onPrivateKeyEntered(String privateKey) {
//                        boolean activate = ActivateApp.activate(MainActivity.this, privateKey);
//                        if(activate){
//                            btnActivate.setVisibility(GONE);
//                            trNewScan.setVisibility(VISIBLE);
//                        }else{
//                            btnActivate.setVisibility(VISIBLE);
//                            trNewScan.setVisibility(GONE);
//                        }
//                    }
//                });
//            }
//        });
//
//        if(AppPreferences.isFirstRun(this)){
//            //1. 第一次启动创建apk独有的密钥对
//            //2. 生成UUID作为设备码， 加密存到本地
//            //3. 用激活需要的公钥sharedPublicKey, 加密uuid, 保存到本地，待激活使用
//            try {
//                KeyStoreHelper.generateKeyPair(this);
//                String uuid = UUID.randomUUID().toString();
//                KeyPair keyPair = KeyStoreHelper.getKeyPair();
//                PublicKey publicKey = keyPair.getPublic();
//                // 使用公钥加密 UUID
//                String encryptedUUID = EncryptionHelper.encryptData(uuid, publicKey);
//                System.out.println("------------- encryptedUUID "+uuid);
//                // 存储加密后的 UUID 到 SharedPreferences
//                AppPreferences.setEncryptedUUID(this, encryptedUUID);
//
//                SharedPublicKey.savePublicKeyToPreferences(this);
//                ActivateApp.encryptUuid(this, uuid);
//
//            } catch (Exception e) {
//                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
//                AppPreferences.reset(this);
//                return;
//            }
//        }
//
//        if(!ActivateApp.isActivate(this)){
//            PrivateKeyInputDialog.showPrivateKeyInputDialog(this, new PrivateKeyInputDialog.PrivateKeyListener() {
//                @Override
//                public void onPrivateKeyEntered(String privateKey) {
//                    boolean activate = ActivateApp.activate(MainActivity.this, privateKey);
//                    if(activate){
//                        btnActivate.setVisibility(GONE);
//                        trNewScan.setVisibility(VISIBLE);
//                    }else{
//                        btnActivate.setVisibility(VISIBLE);
//                        trNewScan.setVisibility(GONE);
//                    }
//                }
//            });
//        }else{
//            btnActivate.setVisibility(GONE);
//            trNewScan.setVisibility(VISIBLE);
//        }
        // //zhy 签名的方式判断激活 --end


        productItemDao = DatabaseClient.getAppDatabase(this).productItemDao();

        btnActivate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PrivateKeyInputDialog.showPrivateKeyInputDialog(MainActivity.this, new PrivateKeyInputDialog.PrivateKeyListener() {
                    @Override
                    public void onPrivateKeyEntered(String privateKey) {
                        boolean activate = ActivateApp.activateByScanner(MainActivity.this, privateKey, manager);
                        if(activate){
                            btnActivate.setVisibility(GONE);
                            trNewScan.setVisibility(VISIBLE);
                        }else{
                            btnActivate.setVisibility(VISIBLE);
                            trNewScan.setVisibility(GONE);
                        }
                    }

                    @Override
                    public void cancle() {
                        btnActivate.setVisibility(VISIBLE);
                        trNewScan.setVisibility(GONE);
                    }
                });
            }
        });


        // 添加布局监听器
//        View rootView = findViewById(android.R.id.content);
//        ViewTreeObserver viewTreeObserver = rootView.getViewTreeObserver();
//        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            @Override
//            public boolean onPreDraw() {
//                // 移除监听器，以确保只在第一次布局变化时执行
//                rootView.getViewTreeObserver().removeOnPreDrawListener(this);
//
//                // 在onResume时隐藏软键盘
//                KeyboardUtils.hideKeyboard(MainActivity.this);
//
//                return true;
//            }
//        });

        //checkActivate();

        // 初始化头部组件
        headerLayout = findViewById(R.id.headerLayout);
        fixedText = findViewById(R.id.fixedText);

        // 初始化内容组件
        contentLayout = findViewById(R.id.contentLayout);
        tableProduct = findViewById(R.id.table_product);

        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

       trElectron1 = findViewById(R.id.tr_electron_1);
        trElectron2 = findViewById(R.id.tr_electron_2);
        trElectron3 = findViewById(R.id.tr_electron_3);
        trElectron4 = findViewById(R.id.tr_electron_4);


        etProductBarcode = findViewById(R.id.et_product_barcode);
        etProductNo = findViewById(R.id.et_product_no);
        etProductNm = findViewById(R.id.et_product_nm);
        imgProduct = findViewById(R.id.img_product);


        etElectronBarcode = findViewById(R.id.et_electron_barcode);
        etElectronNo = findViewById(R.id.et_electron_no);
        etElectronNm = findViewById(R.id.et_electron_nm);
        imgElectron = findViewById(R.id.img_electron);


        etSuccessCount = findViewById(R.id.et_success_count);
        txCheckResult = findViewById(R.id.tx_check_result);
        spinProductNo = findViewById(R.id.spin_product_no);

        // 初始化底部按钮
        // 底部按钮
        LinearLayout bottomLayout = findViewById(R.id.bottomLayout);
        Button btnNewJob = findViewById(R.id.btn_new_job);
        Button btnExport = findViewById(R.id.btn_export);

        // 在这里可以添加其他初始化逻辑或事件监听器
        initData();
        // 设置 Spinner 选择监听器
        spinProductNo.setOnItemSelectedListener(productSelectedListener());

        //TODO 禁用软键盘
        this.etScan.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                    processScanResult();
                    return true;
                }
                return false;
            }
        });

        btnNewJob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newScanJob();
            }
        });

        btnExport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                export2Txt();
                exportAllProducts2Txt();
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    private void checkActivate() {
        if(!ActivateApp.isActivateByScanner(this, manager)){
            PrivateKeyInputDialog.showPrivateKeyInputDialog(this, new PrivateKeyInputDialog.PrivateKeyListener() {
                @Override
                public void onPrivateKeyEntered(String privateKey) {
                    boolean activate = ActivateApp.activateByScanner(MainActivity.this, privateKey, manager);
                    if(activate){
                        btnActivate.setVisibility(GONE);
                        trNewScan.setVisibility(VISIBLE);
                    }else{
                        btnActivate.setVisibility(VISIBLE);
                        trNewScan.setVisibility(GONE);
                    }
                }

                @Override
                public void cancle() {
                    btnActivate.setVisibility(VISIBLE);
                    trNewScan.setVisibility(GONE);
                }
            });
        }else{
            btnActivate.setVisibility(GONE);
            trNewScan.setVisibility(VISIBLE);
        }
    }

    private static final int REQUEST_CODE_EXPORT = 1;

    private final ActivityResultLauncher<Intent> exportLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        Uri uri = data.getData();
                        boolean success = writeToFile(uri, currentContent);// 替换成你的实际内容
                        if(success){
                            clearCurrentProductData();
                        }

                    }
                }else{
                    Toast.makeText(this, "文件导出失败", Toast.LENGTH_SHORT).show();
                }
            }
    );


    private boolean writeToFile(Uri uri, String content) {
        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "wa");
            if (pfd != null) {
                FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
                fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
                fileOutputStream.close();
                pfd.close();
                playAudio("success.mp3");
                new AlertDialog.Builder(this).setTitle("保存").setMessage("保存成功！").setPositiveButton("确定", null).show();
                return true;
            } else {
                Toast.makeText(this, "无法打开输出流", Toast.LENGTH_LONG).show();
            }

            // 使用 ContentResolver 打开输出流
//            OutputStream outputStream = getContentResolver().openOutputStream(uri, "wa");  // "wa" 表示以追加模式打开
//            if (outputStream != null) {
//                // 将内容写入文件
//                outputStream.write(content.getBytes(StandardCharsets.UTF_8));
//                outputStream.close();
//                playAudio("success.mp3");
//                new AlertDialog.Builder(this).setTitle("保存").setMessage("保存成功！").setPositiveButton("确定", null).show();
//                return true;
//            } else {
//                Toast.makeText(this, "无法打开输出流", Toast.LENGTH_LONG).show();
//            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return false;
    }

    private boolean checkWritePermission(Uri uri) {
        // 检查写权限
        int writePermission = getContentResolver().getPersistedUriPermissions().indexOf(uri);
        return writePermission != -1;
    }

    private boolean isDocumentExists(Uri uri) {
        DocumentFile documentFile = DocumentFile.fromSingleUri(this, uri);
        return documentFile != null && documentFile.exists();
    }

    private void exportAllProducts2Txt(){
        progressBar.setVisibility(View.VISIBLE);
        DatabaseManager databaseManager = DatabaseClient.getDatabaseManager();

        databaseManager.execute(new DatabaseManager.DataOperation<String,Boolean>() {

            @Override
            public Boolean execute(String param) {
                Set<String> keys = ProductDB.getProductMap().keySet();
                boolean success = false;
                for (String next : keys) {
                    List<ProductItemEntity> items = productItemDao.getProductItemsByProductNo(next);
                    Product product = ProductDB.getProductMap().get(next);
                    String content = createTextContent(items, product);
                    if ("".equals(content) || product == null) {
                        continue;
                    }
                    String fileName = product.getProjectNo()+"-"+product.getProductNo()
                            +"-"+ DateUtils.getCurrentTime()
                            + ".txt";

                    File appDirectory = getExternalFilesDir(null);
                    FileStorageHelper.saveToFileExternalStorage(appDirectory, fileName, content);
                    success = true;
                }
                return success;
            }

            @Override
            public void onCompleted(Boolean success) {
                if(success){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(GONE);
                            playAudio("success.mp3");
                            new AlertDialog.Builder(MainActivity.this).setTitle("保存").setMessage("保存成功！").setPositiveButton("确定", null).show();
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(GONE);
                            Toast.makeText(MainActivity.this,"没有扫描的数据,请先扫描零件",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(GONE);
                        Toast.makeText(MainActivity.this, "导出失败" + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }, "");
    }

    private void export2Txt() {
        progressBar.setVisibility(View.VISIBLE);
        DatabaseManager databaseManager = DatabaseClient.getDatabaseManager();

        databaseManager.execute(new DatabaseManager.DataOperation<String, List<ProductItemEntity>>() {

            @Override
            public List<ProductItemEntity> execute(String param) {
                return productItemDao.getProductItemsByProductNo(param);
            }

            @Override
            public void onCompleted(List<ProductItemEntity> items) {
                currentContent = createTextContent(items,currentProduct);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(GONE);
                    }
                });
                if(currentContent.equals("")){
                    return;
                }
                selectAndSave();
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(GONE);
                        Toast.makeText(MainActivity.this,"export2Txt err"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, currentProduct.getProductNo());
    }

    private void selectAndSave() {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/plain");
        String fileName = currentProduct.getProjectNo()+"-"+currentProduct.getProductNo()
                +"-"+ DateUtils.getCurrentTime()
                + ".txt";


        intent.putExtra(Intent.EXTRA_TITLE, fileName);  // 指定文件名

        // 指定保存的目录，这里使用Environment.getExternalStorageDirectory()
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(Environment.getExternalStorageDirectory()));

        // 使用 ActivityResultLauncher 启动
        exportLauncher.launch(intent);
    }


    private String createTextContent(List<ProductItemEntity> productItems, Product currentProduct) {
        StringBuilder sb = new StringBuilder();
        int i = 1;
        if(productItems == null || productItems.size() == 0 || null == currentProduct){
            return "";
        }
        for (ProductItemEntity entity : productItems) {
            ProductItem productItem = new ProductItem();
            productItem.setProductNo(currentProduct.getProductNo());
            productItem.setProductBarcode(entity.getProductBarcode());
            productItem.setProductNm(currentProduct.getProductName());
            productItem.setDay(entity.getDateStr());
            productItem.setProjectNo(currentProduct.getProjectNo());
            if(currentProduct.isHasElectron()){
                productItem.setElectronNo(currentProduct.getElectron().getElectronNo());
                productItem.setElectronNm(currentProduct.getElectron().getElectronNm());
                productItem.setElectronPartBarcode(entity.getElectronPartBarcode());
            }
            sb.append(i);
            sb.append("\t ");
            sb.append(productItem.toSeparatedString());
            sb.append("\n");
            i++;
        }
        return sb.toString();
    }
    private String getTextContent() {
        // 显示 ProgressBar
        progressBar.setVisibility(View.VISIBLE);
//        Collection<ProductItemContainer> values = containerMap.values();
        List<ProductItemContainer> values = Collections.singletonList(currentContainer);
        // 客户要按产品导出
        StringBuilder sb = new StringBuilder();
        int i = 1;
        List<ProductItemEntity> productItems = this.productItemDao.getProductItemsByProductNo(currentProduct.getProductNo());
        if(productItems == null || productItems.size() == 0){
            return "";
        }
        for (ProductItemEntity entity : productItems) {
            ProductItem productItem = new ProductItem();
            productItem.setProductNo(currentProduct.getProductNo());
            productItem.setProductBarcode(entity.getProductBarcode());
            productItem.setProductNm(currentProduct.getProductName());
            productItem.setDay(entity.getDateStr());
            productItem.setProjectNo(currentProduct.getProjectNo());
            if(currentProduct.isHasElectron()){
                productItem.setElectronNo(currentProduct.getElectron().getElectronNo());
                productItem.setElectronNm(currentProduct.getElectron().getElectronNm());
                productItem.setElectronPartBarcode(entity.getElectronPartBarcode());
            }
                sb.append(i);
                sb.append("\t ");
                sb.append(productItem.toSeparatedString());
                sb.append("\n");
                i++;
        }
        progressBar.setVisibility(View.INVISIBLE);
        return sb.toString();
    }

//    private void newScanJobOld(){
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("系统提示").setMessage("确定要新扫描么，数据将会被清空？")
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        clearData();
//                        dialog.dismiss();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        dialog.dismiss();
//                    }
//                });
//        AlertDialog dialog = builder.create();
//        dialog.show();
//    }

    private void newScanJob() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.password_dialog, null);
        // 现在你需要修改 AlertDialog.Builder，将这个新的布局设置为对话框的 View
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView)
                .setTitle("新扫描")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 在这里获取输入的密码并验证
                        EditText passwordEditText = dialogView.findViewById(R.id.passwordEditText);
                        String enteredPassword = passwordEditText.getText().toString();
                        if (enteredPassword.equals(YOUR_PASSWORD)) { // 替换成你的实际密码
                            clearData();
                        } else {
                            // 密码错误时的处理
                            Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void clearData() {
        DatabaseClient.getDatabaseManager().execute(new DatabaseManager.DataOperation<String, String>() {

            @Override
            public String execute(String obj) {
                productItemDao.clearTable();
                return "";
            }

            @Override
            public void onCompleted(String value) {

            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"清空数据失败，请重试"+e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        },"");
        containerMap = new LinkedHashMap<>();
        this.setCurrentContainer();
        electronCodes.clear();
        this.resetAllProductComponents();
    }

    private void clearCurrentProductData() {
        if(currentContainer != null){
            List<ProductItem> productItemList = currentContainer.getProductItemList();
            if(productItemList !=null){
                for(ProductItem item : productItemList){
                    electronCodes.remove(item.getElectronPartBarcode());
                }
            }
        }
        currentContainer = new ProductItemContainer();
        containerMap.put(this.currentProduct.getProductNo(), currentContainer);
        this.resetAllProductComponents();
    }

    private void processScanResult() {
        String barcode = this.etScan.getText().toString().trim();
        DatabaseManager databaseManager = DatabaseClient.getDatabaseManager();
        databaseManager.execute(new DatabaseManager.DataOperation<String, Boolean>() {
            @Override
            public Boolean execute(String barcode) {
                return true;
            }

            @Override
            public void onCompleted(Boolean value) {
                ErrorCode errorCode;
                if (operator == 0) {
                    errorCode = currentContainer.setProductItem(barcode, currentProduct, productItemDao);
                    if(errorCode != null){
                        handleErr(errorCode);
                        return;
                    }
                } else {
                    errorCode = currentContainer.setElectronInfo(barcode, currentProduct, productItemDao);
                    if(errorCode != null){
                        handleErr(errorCode);
                        return;
                    }
                    electronCodes.add(barcode);
                }
                handleSuccess();
            }
            @Override
            public void onError(Exception e) {
            }
        },barcode);
    }

    private void handleSuccess() {

        if (operator == 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    etProductBarcode.setText(etScan.getText().toString());
                    if(etProductNo != null){
                        etProductNo.setText(currentProduct.getProductNo());
                    }
                    String displayStr = currentProduct.getProjectNo()+currentProduct.getProductName();
                    etProductNm.setText(displayStr);
                    imgProduct.setImageResource(currentProduct.getImg());
                }
            });

        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    etElectronBarcode.setText(etScan.getText().toString());
                    String displayNo = currentProduct.getElectron().getElectronNo();
                    etElectronNo.setText(displayNo);
                    etElectronNm.setText(currentProduct.getElectron().getElectronNm());
                    imgElectron.setImageResource(currentProduct.getElectron().getImg());
                }
            });
        }
        if(currentContainer.getCurrentProductItem().isSuccess()){
            runOnUiThread(new Runnable() {
                public void run() {
                    txCheckResult.setText(Constants.MSG_SUCCESS);
                    String successCount = String.valueOf(currentContainer.getSuccessCount());
                    etSuccessCount.setText(successCount);
                    txCheckResult.setBackgroundColor(Color.GREEN);
                    playAudio("success.mp3");
                }
            });
            try {
                productItemDao.insertProductItem(new ProductItemEntity(currentContainer.getCurrentProductItem().getProductNo(),
                        currentContainer.getCurrentProductItem().getProductBarcode(), currentContainer.getCurrentProductItem().getElectronPartBarcode()
                        , currentContainer.getCurrentProductItem().getDay()));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "save err", Toast.LENGTH_SHORT).show();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    resetEtScan();
                }
            });
            operator = 0;
        }else{
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    changeOperator(1);
                    resetElectronComponents();
                    etScan.setText("");
                    requestScannerFocus();
                }
            });

        }
    }

    private void resetElectronComponents() {
        this.etElectronBarcode.setText("");
        etElectronNo.setText("");
        etElectronNm.setText("");
        imgElectron.setImageResource(R.drawable.ic_launcher_foreground);
    }


    private void handleErr(ErrorCode errorCode) {
        runOnUiThread(new Runnable() {
            public void run() {
                vibrateDevice();
                txCheckResult.setText(errorCode.getMsg());
                txCheckResult.setBackgroundColor(Color.RED);
                playAudio("warning1.mp3");
                resetEtScan();
                new AlertDialog.Builder(MainActivity.this).setTitle("警告").setMessage(errorCode.getMsg()).setPositiveButton("确定", null).setCancelable(false).show();
            }
        });

    }

    private void resetAllProductComponents(){
        this.changeOperator(0);

        etScan.setText("");
        etProductBarcode.setText("");
        if(etProductNo != null){
            etProductNo.setText("");
        }
        etProductNm.setText("");
        imgProduct.setImageResource(R.drawable.ic_launcher_foreground);

        ctrlElectronComponents();
        etElectronBarcode.setText("");
        etElectronNo.setText("");
        etElectronNm.setText("");
        imgElectron.setImageResource(R.drawable.ic_launcher_foreground);

        etSuccessCount.setText("");
        requestScannerFocus();
    }

    private void resetEtScan() {
        if(operator == 0){
            this.etProductBarcode.setText(this.etScan.getText().toString());
        }else{
            this.etElectronBarcode.setText(this.etScan.getText().toString());
        }
        this.etScan.setText("");
        requestScannerFocus();
    }

    private void requestScannerFocus(){
//        this.etScan.postDelayed(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        etScan.requestFocus();
//                    }
//                }, 500
//        );
        etScan.requestFocus();
    }

    private void changeOperator(int operator){
        this.operator = operator;
        if(this.operator == 0){
            this.txCheckResult.setText(Constants.MSG_HINT_SCAN_P);
        }else{
            this.txCheckResult.setText(Constants.MSG_HINT_SCAN_E);
        }
        this.txCheckResult.setBackgroundColor(Color.GREEN);
    }


    private void initData() {
        this.currentProduct = ProductDB.getProductMap().values().stream().findFirst().get();
        ctrlElectronComponents();
        setCurrentContainer();
        setupSpinnerData();
    }
    private void ctrlElectronComponents(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int visible = GONE;
                if(currentProduct.isHasElectron()){
                    visible = VISIBLE;
                }
                trElectron1.setVisibility(visible);
                trElectron2.setVisibility(visible);
                trElectron3.setVisibility(visible);
                trElectron4.setVisibility(visible);
            }
        });
    }


    private void setCurrentContainer() {
        if(containerMap.get(this.currentProduct.getProductNo())  == null){
            currentContainer = new ProductItemContainer();
            containerMap.put(this.currentProduct.getProductNo(), currentContainer);
        }else{
            currentContainer = containerMap.get(this.currentProduct.getProductNo());
        }
    }

    @NonNull
    private AdapterView.OnItemSelectedListener productSelectedListener() {
        return new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // 处理选择项变化的逻辑
                String selectedItem = parentView.getItemAtPosition(position).toString();
                int index = selectedItem.lastIndexOf("-");
                String productNo = selectedItem.substring(index+1);
                currentProduct = ProductDB.getProductMap().get(productNo);
                setCurrentContainer();
                resetAllProductComponents();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // 在未选择任何项时的处理逻辑
            }
        };
    }


    private void setupSpinnerData() {
        // 准备 Spinner 数据
//        List<String> spinnerData = new ArrayList<>(ProductDB.getProductMap().keySet());
        List<String> spinnerData = new ArrayList<>();
        Set<Map.Entry<String, Product>> entries = ProductDB.getProductMap().entrySet();
        for (Map.Entry<String, Product> data : entries) {
            spinnerData.add(data.getValue().getProjectNo() + "-" + data.getValue().getProductNo());
        }


        // 创建适配器并设置数据
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                spinnerData
        );

        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 将适配器设置到 Spinner 上
        spinProductNo.setAdapter(adapter);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //禁用软键盘
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("系统提示").setMessage("数据可能被清空，确定要退出吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // 用户点击确定，可以执行退出操作
                            finish();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
        return false;
    }

    private void vibrateDevice() {
        // 判断设备是否支持振动
        if (vibrator.hasVibrator()) {
            // 振动持续时间（毫秒）
            long duration = 500;

            // 振动模式，这里是简单的持续振动
            vibrator.vibrate(duration);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        this.requestScannerFocus();
        // 在onResume中显示软键盘
        KeyboardUtils.hideKeyboard(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
    @Override
    protected void onDestroy() {
        DatabaseClient.closeDatabase();
        // 在适当的时候释放振动器资源
        if (vibrator != null) {
            vibrator.cancel();
        }
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        if (manager != null) {
            // close AidcManager to disconnect from the scanner service.
            // once closed, the object can no longer be used.
            manager.close();
        }
        super.onDestroy();
    }

    private void playAudio(String fileName) {
        mediaPlayer = new MediaPlayer();
        try {
            AssetFileDescriptor assetFileDescriptor = getAssets().openFd(fileName);
            mediaPlayer.setDataSource(
                    assetFileDescriptor.getFileDescriptor(),
                    assetFileDescriptor.getStartOffset(),
                    assetFileDescriptor.getLength()
            );
            assetFileDescriptor.close();
            mediaPlayer.prepare();
            mediaPlayer.setVolume(1.0f,1.0f);
            mediaPlayer.start();
            // 为了释放资源，您可以在音频播放完成后调用 mediaPlayer.release() 或者在适当的时机调用
            mediaPlayer.setOnCompletionListener(MediaPlayer::release);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}